// 复原IP地址

package Leetcode;

import java.util.ArrayList;
import java.util.List;

class solution_093 {
    public List<String> restoreIpAddresses(String s) {
        List<String> result = new ArrayList<>();
        BackTrace(result, s, 0, new ArrayList<String>());
        return result;
    }

    public void BackTrace(List<String> result, String s, int currentLoc, List<String> combination) {
        // 当遍历完成时，组合数应该正好为4
        if (currentLoc == s.length() && combination.size() == 4) {
            String str = String.join(".", combination);
            result.add(str);
            return;
        }
        // 遍历完成或者组合数越界直接返回
        if (currentLoc > s.length() || combination.size() > 4) {
            return;
        }
        // 注意等于号
        if (currentLoc < s.length() && combination.size() <= 4) {
            int size = combination.size();
            if (size == 0) {
                combination.add(String.valueOf(s.charAt(currentLoc)));
                BackTrace(result, s, currentLoc + 1, combination);
                combination.remove(combination.size() - 1);
            } else {
                String last = combination.get(combination.size() - 1);
                String lastAdd = last + s.charAt(currentLoc);
                int sum = 0;
                for (char c : lastAdd.toCharArray()) {
                    sum = sum * 10 + (c - '0');
                }
                // System.out.println(sum);
                // 两种情况，要么加在前面的字符串里，要么直接称为新的字符串。
                // 如果前面不为0且加入后小于255则可以加上
                if (!last.equals("0") && lastAdd.length() <= 3 && sum <= 255) {
                    combination.remove(combination.size() - 1);
                    combination.add(lastAdd);
                    BackTrace(result, s, currentLoc + 1, combination);
                    combination.remove(combination.size() - 1);
                    combination.add(last);
                }
                // 直接称为一个新的字符串
                combination.add(String.valueOf(s.charAt(currentLoc)));
                BackTrace(result, s, currentLoc + 1, combination);
                combination.remove(combination.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        // String s1 = new String("26");
        // String s2 = new String("12");
        // String s3 = new String("255");
        // System.out.println(s1.compareTo(s3));
        String s = "25525511135";
        solution_093 s093 = new solution_093();
        List<String> list = s093.restoreIpAddresses(s);
        for(String str : list)
            System.out.println(str);
    }
}

public class Solution093 {

}
